<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <meta content="email=no" name="format-detection">
    <title>临停缴费</title>

    <link rel="stylesheet" href="../css/weui.css" />
    <link rel="stylesheet" href="../css/example.css" />
    <link rel="stylesheet" href="../css/plate.css" />
    <link rel="stylesheet" href="../css/common.css" />
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <style>
        html,
        body {
            font-family: 'PingFangSC-Regular';
            width: 100%;
            height: 99%;
            background: #F5F5F9;
            color: rgba(51, 51, 51, 0.87);
            margin: 0;
            overflow-y: auto;
        }

        .weui-tab {
            height: 14vh;
            background-color: blue;
            display: flex;
            justify-content: center;
            align-items: flex-end;
        }

        .page__hd {
            padding: 0px;
        }

        .car {
            width: 30px;
        }

        .weui-cells {
            margin-top: 0px;
        }

        .weui-cell {
            display: flex;
            align-items: center;
        }

        .weui-cells>.weui-cell>p {
            color: #333333;
        }

        .weui-btn:after {
            border: none;
        }

        .hhead {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .wechatpay {
            width: 24px;
            height: 24px;
            margin-right: 10px;
        }

        .parking_name {
            color: black;
            font-weight: 500;
            margin: 0px 6px 0px 6px;
        }

        .temp_parking {
            color: white;
            font-size: 10px;
            background-color: #00b4bb;
            padding: 3px 7px 3px 7px;
            margin-left: 4px;
            border-radius: 6px;
        }

        .total_money {
            font-size: 20px;
            color: #0051bc;
            margin: 0px 4px 0px 4px;
            font-weight: 600;
        }

        .ffooter {
            display: flex;
            align-items: center;
        }

        .wechat_pay {
            display: flex;
            align-items: center;
        }

        .weui-btn {
            border-radius: 6px;
        }

        .gopay {
            background-color: #0051bc;
            color: white;
        }

        .cancel {
            color: #bababa;
            background-color: #F5F5F9;
            border: 1px solid #c4c4c4;
        }
    </style>
</head>

<body>
    <div id="main">
        <div class="weui-cells" style="margin-top: 0px;">
            <div class="weui-cell hhead">
                <img class="car" src="../images/car@2x.png" alt="">
                <span id="car_num" class="parking_name"></span>
                <span class="temp_parking">临停车</span>
            </div>
        </div>

        <div class="weui-cells" style="margin-top: 10px;">
            <div class="weui-cell borderbottom">
                <div class="weui-cell__bd">
                    <p>进场时间</p>
                </div>
                <div class="weui-cell__ft" id="intime"></div>
            </div>
            <div class="weui-cell borderbottom">
                <div class="weui-cell__bd">
                    <p>停车时长</p>
                </div>
                <div class="weui-cell__ft"><span id="duration"></span></div>
            </div>

            <div class="weui-cell">
                <div class="weui-cell__bd">
                    <p>应付停车费</p>
                </div>
                <div class="weui-cell__ft ffooter">
                    <span id="actual_money" class="total_money"></span>
                    元
                </div>
            </div>
        </div>

        <div class="weui-cells" style="margin-top: 10px;">
            <div class="weui-cell">
                <div class="weui-cell__bd">
                    <p>支付金额</p>
                </div>
                <div class="weui-cell__ft wechat_pay">
                    <img class="wechatpay" src="../images/wechat_payment@2x.png" alt="">
                    <span id="wechat_pay" class="unit">微信支付</span>
                </div>
            </div>
        </div>

        <div class="page__bd page__bd_spacing" style="margin-top: 45px;">
            <a id="gopay" class="weui-btn gopay">支付</a>
            <a id="cancel" class="weui-btn cancel">取消</a>

            <!-- <div class="weui-footer weui-footer_fixed-bottom">
                <p>请于<span id="leave_time">15</span>分钟内完成付款并离场，超时将加收停车费</p>
                <div>
                    <p>本服务由江苏慧泽提供</p>
                    <p>联系电话:<a href="tel:4009015600">400-901-5600</a></p>
                </div>
            </div> -->
        </div>


        <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
        <script src="../js/jquery-1.11.3.min.js"></script>
        <script src="../js/common.js"></script>
        <script src="../js/moment.min.js"></script>
        <script src="../js/base64.js"></script>

        <script>
            //code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
            // var auth_code = get_querystring("code");

            // var plate = get_querystring('plate');
            //openid和plate是全局变量
            // var openid = null;
            // var plate = null;

            // var price = null;
            // var coupon = null;

            var auth_code = get_querystring("auth_code") || get_querystring("code") || undefined;
            var state = get_querystring("state");
            var area = null;
            var openid = get_querystring("openid");
            var plate = get_querystring("plate");
            var billdata = null;
            var coupon = null;

            var out_trade_no = null;

            if (!plate && state) {
                plate = JSON.parse(Base64.decode(state)).plate;
            }
            plate = plate && plate.trim().toUpperCase() || null;


            //允许支付按钮的单击功能
            function enable_pay() {
                $("#gopay").unbind();
                $('#gopay').removeClass('cancel');
                $('#gopay').addClass('gopay');
                $("#gopay").bind("click", do_pay);
            }

            //取消支付按钮的单击功能
            function disable_pay() {
                $('#gopay').removeClass("gopay").addClass('cancel');
                $("#gopay").unbind();
            }

            function query_user() {
                var data = {
                    openid: openid,
                    auth_code: auth_code
                };
                var url = hostname + rest_domain + '/wechat/user/usermanager';
                $.ajax({
                    type: 'get',
                    url: url,
                    data: data,
                    timeout: 3 * 1000,
                    success: function (result, textStatus) {
                        var data = result.data;
                        if (data) {
                            localStorage.setItem('userinfo', JSON.stringify(result.data));
                        }
                        var uesrinfo = JSON.parse(localStorage.getItem('userinfo'));
                        var plates = uesrinfo.plates
                        draw_userplates(plates);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert('query user failed');
                    }
                });
            }

            function draw_userplates(userplate) {
                var plates = JSON.stringify(userplate);
                for (var key in userplate) {
                    var last_plate = JSON.stringify(key);
                }
                var car_num = last_plate.replace(/\"/g, "");
                next(car_num);
                $('#car_num').html(car_num);
            }


            function config(data) {
                var config_info = {
                    debug: false,
                    appId: data.appId,
                    timestamp: data.timestamp,
                    nonceStr: data.nonceStr,
                    signature: data.signature,
                    jsApiList: ["chooseWXPay"]
                }
                try {
                    wx.config(config_info);

                } catch (e) {
                    log(e.message);
                }
                wx.ready(function () {
                    // alert("获取JSAPI的配置成功");
                });
                wx.error(function (res) {
                    alert('设置微信配置失败：' + res.errMsg);
                });
            }

            //获取JSAPI的配置
            function get_config() {
                $.ajax({
                    type: "POST",
                    timeout: 3 * 1000,
                    url: `${hostname}${rest_domain}/mobilepay/wechat/parking/config`,
                    data: {
                        area: area,
                        url: window.location.href
                    },
                    processData: true,
                    dataType: "json",
                    success: function (result, textStatus) {
                        if (!result || !result.result) {
                            alert(result && result.message || '获取配置失败');
                            WeixinJSBridge.call('closeWindow');
                        }
                        var data = result.data;
                        config(data);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("获取配置错误");
                    }
                });
            }


            //查询账单
            function query_bill() {
                $.ajax({
                    type: 'GET',
                    timeout: 3 * 1000,
                    url: `${hostname}${rest_domain}/mobilepay/wechat/parking/bill`,
                    data: {
                        auth_code: auth_code,
                        openid: openid,
                        area: area,
                        plate: plate,
                        couponid: coupon && coupon.id || undefined,
                        state: state,
                        config: window.location.href
                    },
                    success: function (resp) {
                        if (!resp || !resp.result) {
                            alert('查询支付账单失败11111111');
                            return;
                        }
                        var data = resp.data;
                        billdata = data;
                        out_trade_no = billdata.out_trade_no;
                        //先判断停车事件是不是为0
                        var in_duration = billdata.in_duration;
                        if (!in_duration) {
                            in_duration = 0;
                        }
                        //停车时间格式转换
                        var in_hour = parseInt(in_duration / 3600);
                        var in_minute = Math.ceil((in_duration % 3600) / 60);
                        var duration = human_time(in_duration);
                        //车牌号
                        $("#car_num").html(data.car_number);
                        //进场时间
                        $("#intime").html(data.in_time);
                        //停车时长
                        $("#duration").html(duration);
                        //实际要付的金额
                        $("#actual_money").html(((data.unpaid_amount) / 100).toFixed(2));
                        var actual_money = ((data.unpaid_amount) / 100).toFixed(2);
                        if (data.redirect) {
                            window.location.href = data.redirect;
                            return;
                        }
                        openid = data.openid;
                        sessionStorage.setItem("openid", openid);

                        if (actual_money > 0) {
                            enable_pay();
                        }

                        if (data.config) {
                            config(data.config);
                            delete data.config;
                        }
                        else {
                            get_config();
                        }
                    },
                    error: function (resp) {
                        alert('no connected');
                        alert(resp.message);
                    }
                });
            }

            //支持微信支付
            function do_pay() {
                if (!billdata || !(billdata.unpaid_amount >= 0)) {
                    return;
                }
                disable_pay();
                var url = hostname + rest_domain + "/mobilepay/wechat/parking/trade";

                $.ajax({
                    type: "POST",
                    timeout: 5 * 1000,
                    url: url,
                    data: billdata,
                    processData: true,
                    dataType: "json",
                    success: function (resp) {
                        if (!resp || !resp.result) {
                            alert(resp && resp.message || '创建支付账单失败');
                            return;
                        }
                        var data = resp.data;
                        if (data.status == 'PAY') {
                            alert('zll 支付成功');
                        }
                        else if (data.return_code == "SUCCESS") {
                            //这里的函数属于什么？？？
                            //timestamp支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写
                            //但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                            //nonceStr支付签名随机串，不长于 32 位
                            //package统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                            //signType签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                            //paySign支付签名
                            // res.errMsg === 'chooseWXPay:ok'方式判断前端返回,微信团队郑重提示：
                            // res.errMsg将在用户支付成功后返回ok，但并不保证它绝对可靠， 切记
                            var app_id = data.appid;
                            var prepay_id = data.prepay_id;
                            var timestamp = data.timestamp;
                            var nonceStr = data.nonce_str;
                            var sign = data.sign;
                            var sign_type = data.sign_type;
                            //以上所有的值都会显示
                            // alert('app_id == ' + app_id);
                            // alert('prepay_id == ' + prepay_id);
                            // alert('支付签名时间戳timetamp == ' + timestamp);
                            // alert('支付签名随机串nonceStr == ' + nonceStr);
                            // alert('sign == ' + sign);
                            // alert('sign_type == ' + sign_type);
                            var pay_info = {
                                appId: app_id,
                                timestamp: timestamp,
                                nonceStr: nonceStr,
                                package: 'prepay_id=' + prepay_id,
                                signType: sign_type,
                                paySign: sign,
                                success: function (res) {
                                    query_payment();
                                },
                                fail: function (res) {
                                    alert("执行支付失败：" + res.errMsg);
                                }
                            };
                            wx.chooseWXPay(pay_info);
                            wx.error(function (res) {
                                alert("执行支付失败：" + res.errMsg);
                            });
                        }
                    },
                    error: function (xhr, type) {
                        alert('do pay failed');
                        alert(xhr);
                    }
                });
            }

            //查询支付结果
            function query_payment() {
                $.ajax({
                    type: 'GET',
                    timeout: 5 * 1000,
                    url: hostname + rest_domain + "/mobilepay/wechat/parking/pay_query",
                    data: { out_trade_no: out_trade_no },
                    success: function (resp) {
                        // log(JSON.stringify(resp))
                        if (!resp || !resp.result) {
                            alert('查询支付账单失败');
                        }
                        window.location.href = `success_pay.html?plate=${plate}`;

                    },
                    error: function (resp) {
                        alert('查询支付账单失败');
                        alert(resp);
                        WeixinJSBridge.call('closeWindow');
                    }
                });
            }

            $(function () {
                //获取车牌号所在的项目号
                $.ajax({
                    type: "GET",
                    timeout: 3 * 1000,
                    url: `${hostname}${rest_domain}/mobilepay/wechat/parking/area?plate=${plate}&state=${state}`,
                    success: function (result, status) {
                        if (!result || !result.result) {
                            alert(result && result.message || '获取车牌号所在停车场失败');
                            window.history.back();
                            return;
                        }
                        area = parseInt(result.data);
                        query_bill();
                        querycoupon();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                        alert("获取车牌号所在停车场失败");
                        window.history.back();
                    }
                });

                // $('#cancel').click(function () {
                //     window.location.href = 'nomoney_car.html';
                // });

            })


        </script>
</body>

</html>